package com.megvii.corelib.base;

/**
 * Created by linyue on 15/12/24.
 */

import android.content.Context;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.megvii.corelib.util.MegviiToast;

import de.greenrobot.event.EventBus;

/**
 * 子类必须有public的默认构造函数
 * @param <VIEW>
 */
public abstract class MegviiPresenter<VIEW extends PresenterHolder> implements Response.ErrorListener
{
    protected VIEW viewHolder;

    protected Context context;

    public static <PRESENTER extends MegviiPresenter> PRESENTER buildPresenter(
            Class<PRESENTER> presenterClass)
    {
        try
        {
            return presenterClass.newInstance();
        }
        catch (InstantiationException e)
        {
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    protected void doInit(VIEW view)
    {
        this.viewHolder = view;
        this.context = view.getContextX();
        EventBus.getDefault().register(this);
    }

    /**
     * 功能：<br/>
     * 1、弹错误提示框<br/>
     * 2、隐藏progress bar<br/>
     *
     * @param error
     */
    @Override
    public void onErrorResponse(VolleyError error)
    {
        if (error != null)
        {
            if (error.networkResponse != null)
            {
                showToast(new String(error.networkResponse.data));
            }
            else
            {
                showToast("您的网络不稳定，请重试");
            }
        }
        if (viewHolder != null)
        {
            viewHolder.hideProgressBar();
        }
        else
        {
            Log.d("Volley", "why is viewHolder null ???");
        }
        //
        viewHolder.showNetworkError();
    }

    public void showToast(String text)
    {
        MegviiToast.showToast(context, text);
    }

    protected void onDestory()
    {
        EventBus.getDefault().unregister(this);
    }

    protected abstract void onCreated();

    protected abstract void onResume();

    protected abstract void onPause();

    protected void onStart()
    {

    }

    protected void onStop()
    {

    }

    public abstract void onClickRefreshNetwork();

    public void onEvent(Object o)
    {

    }
}
